package com.wwg.myapplication;

import android.content.Context;
import android.graphics.*;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.animation.ValueAnimator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WaterRippleScreen extends View {
    // 画笔定义
    private Paint ripplePaint;    // 波纹边缘画笔
    private Paint waterPaint;     // 水膜填充画笔
    private Paint residuePaint;   // 残留水痕画笔
    private Paint glowPaint;      // 水膜反光画笔

    // 颜色配置
    private int rippleColor = 0x7064B5F6;   // 波纹边缘色（半透明蓝）
    private int waterColor = 0x3090CAF9;    // 水膜填充色（淡蓝）
    private int residueColor = 0x15E3F2FD;  // 残留水痕色（极淡蓝）
    private int glowColor = 0x40FFFFFF;     // 水膜反光色（半透明白）

    // 数据集合
    private List<Ripple> ripples = new ArrayList<>();       // 活跃波纹
    private List<Residue> residues = new ArrayList<>();     // 残留水痕

    // 屏幕尺寸
    private int screenWidth;
    private int screenHeight;

    // 控制参数
    private boolean autoGenerate = true;    // 是否自动生成水滴
    private float residueDecay = 0.002f;    // 水痕衰减速度
    private boolean enableResidue = true;   // 是否启用残留水痕
    private Random random = new Random();

    public WaterRippleScreen(Context context) {
        super(context);
        init();
    }

    public WaterRippleScreen(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        initPaints();

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                screenWidth = getWidth();
                screenHeight = getHeight();
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        // 启动严格的3秒间隔生成器
        startStrictIntervalGenerator();
    }

    private void initPaints() {
        // 波纹边缘画笔
        ripplePaint = new Paint();
        ripplePaint.setColor(rippleColor);
        ripplePaint.setStyle(Paint.Style.STROKE);
        ripplePaint.setStrokeCap(Paint.Cap.ROUND);
        ripplePaint.setAntiAlias(true);

        // 水膜填充画笔
        waterPaint = new Paint();
        waterPaint.setColor(waterColor);
        waterPaint.setStyle(Paint.Style.FILL);
        waterPaint.setAntiAlias(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            waterPaint.setBlendMode(BlendMode.SRC_ATOP);
        }

        // 残留水痕画笔
        residuePaint = new Paint();
        residuePaint.setColor(residueColor);
        residuePaint.setStyle(Paint.Style.FILL);
        residuePaint.setAntiAlias(true);
        residuePaint.setMaskFilter(new BlurMaskFilter(15, BlurMaskFilter.Blur.NORMAL));

        // 水膜反光画笔
        glowPaint = new Paint();
        glowPaint.setColor(glowColor);
        glowPaint.setStyle(Paint.Style.FILL);
        glowPaint.setAntiAlias(true);
    }

    /**
     * 严格控制3秒生成一个水波（解决过多问题）
     */
    private void startStrictIntervalGenerator() {
        // 使用固定间隔的ValueAnimator，确保严格3秒一次
        ValueAnimator animator = ValueAnimator.ofInt(0, 1);
        animator.setDuration(3000); // 固定3秒间隔
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setStartDelay(1000); // 初始延迟1秒，避免启动瞬间生成
        animator.addUpdateListener(animation -> {
            // 仅在视图可见且尺寸有效时生成
            if (autoGenerate && isShown() && screenWidth > 0 && screenHeight > 0) {
                int x = random.nextInt(screenWidth);
                int y = random.nextInt(screenHeight);
                // 生成稍大的水波，弥补数量减少的视觉影响
                float size = 6 + random.nextFloat() * 4;
                createRipple(x, y, size, false);
            }
        });
        animator.start();
    }

    public void createRipple(float x, float y, float initialSize, boolean isTouch) {
        ripples.add(new Ripple(x, y, initialSize, isTouch));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawResidues(canvas);
        drawRipples(canvas);
        invalidate();
    }

    private void drawResidues(Canvas canvas) {
        if (residues.isEmpty()) return;

        List<Residue> copy = new ArrayList<>(residues);
        for (Residue residue : copy) {
            residue.alpha -= residueDecay * 255;
            if (residue.alpha <= 0) {
                residues.remove(residue);
                continue;
            }

            residuePaint.setAlpha((int) residue.alpha);
            canvas.drawCircle(residue.x, residue.y, residue.radius, residuePaint);
        }
    }

    private void drawRipples(Canvas canvas) {
        if (ripples.isEmpty()) return;

        List<Ripple> copy = new ArrayList<>(ripples);
        for (Ripple ripple : copy) {
            if (!ripple.update()) {
                if (enableResidue) {
                    residues.add(new Residue(ripple.x, ripple.y, ripple.currentRadius * 0.8f));
                }
                ripples.remove(ripple);
                continue;
            }

            waterPaint.setAlpha(ripple.waterAlpha);
            canvas.drawCircle(ripple.x, ripple.y, ripple.currentRadius * 0.7f, waterPaint);

            ripplePaint.setStrokeWidth(ripple.strokeWidth);
            ripplePaint.setAlpha(ripple.edgeAlpha);
            canvas.drawCircle(ripple.x, ripple.y, ripple.currentRadius, ripplePaint);

            drawRippleGlow(canvas, ripple);
        }
    }

    private void drawRippleGlow(Canvas canvas, Ripple ripple) {
        if (ripple.currentRadius < 20) return;

        float glowX = ripple.x + (float) Math.sin(ripple.life * 1.5) * ripple.currentRadius * 0.2f;
        float glowY = ripple.y - ripple.currentRadius * 0.2f;

        RectF glowOval = new RectF(
                glowX - ripple.currentRadius * 0.3f,
                glowY - ripple.currentRadius * 0.1f,
                glowX + ripple.currentRadius * 0.3f,
                glowY + ripple.currentRadius * 0.1f
        );
        glowPaint.setAlpha((int) (ripple.edgeAlpha * 0.7));
        canvas.drawOval(glowOval, glowPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float y = event.getY();
                createRipple(x, y, 8 + random.nextFloat() * 4, true);
                return true;
        }
        return super.onTouchEvent(event);
    }

    private class Ripple {
        float x, y;
        float initialSize;
        float currentRadius;
        float maxRadius;
        float speed;
        float life = 0;
        int edgeAlpha;
        int waterAlpha;
        float strokeWidth;

        Ripple(float x, float y, float initialSize, boolean isTouch) {
            this.x = x;
            this.y = y;
            this.initialSize = initialSize;
            this.currentRadius = initialSize;

            if (isTouch) {
                maxRadius = 120 + random.nextFloat() * 80;
                speed = 1.8f + random.nextFloat() * 0.8f;
                strokeWidth = initialSize * 1.2f;
            } else {
                // 自动生成的水波扩散范围更大，弥补数量减少的不足
                maxRadius = 100 + random.nextFloat() * 60;
                speed = 1.0f + random.nextFloat() * 0.5f; // 速度稍慢，延长显示时间
                strokeWidth = initialSize * 1.0f;
            }
        }

        boolean update() {
            life += speed * 0.01f;
            currentRadius = initialSize + (float) (maxRadius * (1 - Math.exp(-life * 0.4)));

            edgeAlpha = (int) (200 * (1 - life / 3f));
            waterAlpha = (int) (100 * (1 - life / 2.5f));

            return edgeAlpha > 15 && currentRadius < maxRadius;
        }
    }

    private class Residue {
        float x, y;
        float radius;
        float alpha = 255;

        Residue(float x, float y, float radius) {
            this.x = x;
            this.y = y;
            this.radius = radius;
        }
    }

    // 外部控制方法
    public void setAutoGenerate(boolean autoGenerate) {
        this.autoGenerate = autoGenerate;
    }

    public void setResidueDecay(float decay) {
        this.residueDecay = decay;
    }

    public void setEnableResidue(boolean enable) {
        this.enableResidue = enable;
    }
}